package classLoader;

import java.io.*;
import java.net.URLClassLoader;

/**
 * 自定义类加载器，加载自定义目录下的文件
 *
 * @Author: zhangzhiwei
 * @Date: 2022/1/11 22:03
 */
public class MyClassLoader extends ClassLoader {

    private String path;

    public MyClassLoader(String path){
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) {
        // 获取二进制文件流
        File file = new File(path);
        Class<?> defineClass = null;
        byte[] bytes = getClassBytes(path);;
        // 获取servlet名字
        //String servletName = path.substring(path.lastIndexOf(File.separator) + 1, path.indexOf("."));
        // 加载字节码文件生成Class对象
        defineClass = defineClass(name, bytes, 0, bytes.length);
        return defineClass;

    }

    private byte[] getClassBytes(String name) {

        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(name);
            out = new ByteArrayOutputStream();
            byte[] buf = new byte[2048];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
